/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import control.ShopFacade;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.StringConverter;
import jpamodel.Category;
import jpamodel.OwnedWare;

/**
 *
 * @author Hans
 */
public class OwnedWaresView extends VBox {

    private TableView<OwnedWare> table;
    private ObservableList<OwnedWare> datalist;// = FXCollections.observableArrayList();
    private ObservableList<OwnedWare> sortedList;
    private Text text;
    private TableColumn<OwnedWare, String> name;
    private TableColumn<OwnedWare, Number> purchasePrice;
    private TableColumn<OwnedWare, Number> priceColumn;
    private TableColumn<OwnedWare, LocalDate> dateIn;
    private TableColumn<OwnedWare, LocalDate> dateOut;
    private DateTimeFormatter myDateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    private ComboBox<Category> categoryCombo;
    private ShopFacade shop;
    private HBox top;
    private ObservableList<Category> cats;
    private OwnedWare selectedWare;
    private Button editPrice;
    private Button sellWare;
    private Label wareName;
    private TextField newPrice;
    private Button deleteWare;

    public OwnedWaresView(ObservableList<OwnedWare> data, ShopFacade shop) {
        this.dateOut = new TableColumn<>("Dato solgt");
        this.dateIn = new TableColumn<>("Dato købt");
        this.priceColumn = new TableColumn<>("Pris");
        this.purchasePrice = new TableColumn<>("Indkøbspris");
        this.name = new TableColumn<>("Vare");
        this.table = new TableView<>();
        this.datalist = data;
        this.shop = shop;
        this.sortedList = FXCollections.observableArrayList();
        if (shop.getDBC().isConnected()) {
            datalist = shop.getAllOwnedWares();
            datalist.stream().forEach((ware) -> {
                sortedList.add(ware);
            });
            cats = shop.getCategories(true);
        }
        this.setPadding(MainView.INSETS);
        table.getColumns().add(name);
        table.getColumns().add(purchasePrice);
        table.getColumns().add(priceColumn);
        table.getColumns().add(dateIn);
        table.getColumns().add(dateOut);
        name.prefWidthProperty().bind(table.widthProperty().multiply(0.30));
        purchasePrice.prefWidthProperty().bind(table.widthProperty().multiply(0.15));
        priceColumn.prefWidthProperty().bind(table.widthProperty().multiply(0.15));
        dateIn.prefWidthProperty().bind(table.widthProperty().multiply(0.20));
        dateOut.prefWidthProperty().bind(table.widthProperty().multiply(0.20));
        name.setCellValueFactory(c -> c.getValue().nameProperty());
        purchasePrice.setCellValueFactory(c -> c.getValue().purchasePriceProperty());
        priceColumn.setCellValueFactory(c -> c.getValue().soldPriceProperty());
        priceColumn.getStyleClass().add("numbercolums");
        purchasePrice.getStyleClass().add("numbercolums");
        dateIn.setCellValueFactory(c -> c.getValue().dateInProperty());
        dateIn.setCellFactory(c -> {
            return new TableCell<OwnedWare, LocalDate>() {
                @Override
                protected void updateItem(LocalDate item, boolean empty) {
                    super.updateItem(item, empty);

                    if (item == null || empty) {
                        setText(null);
                        setStyle("");
                    } else {
                        // Format date.
                        setText(myDateFormatter.format(item));
                    }
                }
            };
        });
        dateOut.setCellValueFactory(c -> c.getValue().dateOutProperty());
        dateOut.setCellFactory(c -> {
            return new TableCell<OwnedWare, LocalDate>() {
                @Override
                protected void updateItem(LocalDate item, boolean empty) {
                    super.updateItem(item, empty);

                    if (item == null || empty) {
                        setText(null);
                        setStyle("");
                    } else {
                        // Format date.
                        setText(myDateFormatter.format(item));
                    }
                }
            };
        });
//        category.setMinWidth(60);
        //name.setMinWidth(160);
        purchasePrice.setMinWidth(95);
        //  price.setMinWidth(80);
        //  dateIn.setMinWidth(120);
        //  dateOut.setMinWidth(120);
        this.text = new Text("* Egne Varer *");
        text.setFont(MainView.getFont());
        table.setPrefWidth(MainView.WIDTH);
        table.setItems(sortedList);
        table.getStyleClass().add("table");
        setupComboBox();
        top = new HBox(text, categoryCombo);
        top.setSpacing(20);
        this.getChildren().addAll(top, table);
        setupButtons();

        table.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> selectedWare(newValue));

//        setupDemoRows();
    }

    public void update() {
        if (shop.getDBC().isConnected()) {
            cats = shop.getCategories(false);
            categoryCombo.setItems(cats);
            datalist = shop.getAllOwnedWares();
            sortedList.clear();
            datalist.stream().forEach((ware) -> {
                sortedList.add(ware);
            });
        }
        table.getColumns().get(0).setVisible(false);
        table.getColumns().get(0).setVisible(true);
    }

    private void setupButtons() {
        wareName = new Label(" ");
        sellWare = new Button("Sælg Vare");
        sellWare.getStyleClass().add("mybutton");
        editPrice = new Button("Ny Pris");
        editPrice.getStyleClass().add("mybutton");
        newPrice = new IntegerTextField();
        HBox priceBox = new HBox(editPrice, newPrice);
        priceBox.setSpacing(20);
        deleteWare = new Button("Slet Vare");
        deleteWare.getStyleClass().add("mybutton");
        this.getChildren().addAll(wareName, sellWare, priceBox, deleteWare);

        sellWare.setOnAction(event -> {
            if (selectedWare != null && selectedWare.isUnsold()) {
                selectedWare.setDateOut(LocalDate.now());
                shop.persist(selectedWare);
            }
        });

        editPrice.setOnAction(event -> {
            if (selectedWare != null && selectedWare.isUnsold() && !newPrice.getText().isEmpty()) {
                int price = Integer.parseInt(newPrice.getText());
                selectedWare.setSoldPrice(price);
                shop.persist(selectedWare);
                newPrice.clear();
            }
        });

        deleteWare.setOnAction(event -> {
            if (selectedWare != null) {
                shop.remove(selectedWare);
                datalist.remove(selectedWare);
                sortedList.remove(selectedWare);
            }
        });
    }

    private void selectedWare(OwnedWare selectThis) {
        if (selectThis != null) {
            selectedWare = selectThis;
            System.out.println(selectedWare);
        } else {
            System.out.println("BLAH");
        }
    }

    private void setupComboBox() {
        categoryCombo = new ComboBox<>();
        categoryCombo.setPromptText("Vælg Kategori");
        categoryCombo.setItems(cats);
        categoryCombo.getStyleClass().add("combobox");
        categoryCombo.setCellFactory((comboBox) -> {
            return new ListCell<Category>() {
                @Override
                protected void updateItem(Category item, boolean empty) {
                    super.updateItem(item, empty);

                    if (item == null || empty) {
                        setText(null);
                    } else {
                        setText(item.getName() + " (" + item.getOwnedWareList().size() + ")");
                    }
                }
            };
        });
        categoryCombo.setConverter(new StringConverter<Category>() {
            @Override
            public String toString(Category category) {
                if (category == null) {
                    return null;
                } else {
                    return category.getName() + " (" + category.getOwnedWareList().size() + ")";
                }
            }

            @Override
            public Category fromString(String personString) {
                return null;
            }
        });
        categoryCombo.setOnAction(event -> {
            Category selected = categoryCombo.getSelectionModel().getSelectedItem();
            sortedList.clear();
            datalist.stream().filter((ware) -> (selected.equals(cats.get(0)) || ware.getCategory().equals(selected))).forEach((ware) -> {
                sortedList.add(ware);
            });
            table.setItems(sortedList);
        });
    }
}
